#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Filename: college_import.py
# LD (2009/09/29)
import MySQLdb,os

# 执SQL语句		
def execSQl(conn, sql, type = 1):
	if len(sql) > 0:
		cur = conn.cursor()
		if type == 2:
			cur.callproc(sql)
		else:
			cur.execute(sql)
		conn.commit()
		cur.close()

##默认的备份list路径 (确定目录有写权限)
backup_path = '/root/college/old'
data = '2009-09-29'
mysql_user = 'wgz' #Mysql用户，留空则不进行数据库保存，使用root可以避免权限问题
mysql_pass = '123456' #上面指定用户的密码
mysql_db = {'core_auth':'auth',
			'kkyoo_account':'kkyoo_account',
			'kkyoo_admin':'kkyoo_admin',
			'kkyoo_gift':'kkyoo_gift',
			'kkyoo_grade':'kkyoo_grade',
			'kexoo_im':'kkyoo_im',
			'kkyoo_kbao':'kkyoo_kbao',
			'kkyoo_kcard':'kkyoo_kcard',
			'kkyoo_rank':'kkyoo_rank',
			'kyoo_rooms':'kkyoo_rooms',
			'kkyoo_storage':'kkyoo_storage',
			'kkyoo_store':'kkyoo_store'} 
			#数据库，数据库名
mysql_cmd = '`which mysql`' #不同系统可能有所不同，尤其是自己编译的
# 也可自己加入路径，如： '/usr/bin/mysql'
mysql_charset = 'utf8' #数据库编码
####################

conn = MySQLdb.Connection('localhost', mysql_user, mysql_pass)
execSQl(conn, 'SET NAMES utf8')
			
for i in mysql_db.keys():
		db_name=backup_path+os.sep+mysql_db[i]+'_'+data+'.sql'
		
		sql = "DROP database IF EXISTS %s " %(i)
		execSQl(conn, sql)
		print sql
		sql2 = "CREATE database %s " %(i)
		execSQl(conn, sql2)
		print sql2
		db_command="%s -u%s -p%s --default-character-set=%s -D %s < %s" % \
				(mysql_cmd,mysql_user,mysql_pass,mysql_charset,i,db_name)
		if os.system(db_command) == 0:
			print "Import Database %s" %(mysql_db[i])
		else: 
			print "Failed Database %s" %(mysql_db[i])

conn.close()
print "DATABASE IMPORT OVER!"
#FILE DONE